package com.sllp.C71S3TsllpShop.util;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.springframework.stereotype.Component;

import com.sllp.C71S3TsllpShop.bean.ChartData;
import com.sllp.C71S3TsllpShop.bean.OrdersItem;

@Component
public class GenerateOrdersItemChartData {

	/**
	 * 获得订单的统计图表数据
	 * @param ordersItems 未处理的订单集合
	 * @return
	 */
	public List<ChartData> generateOrdersItemChartData(List<OrdersItem> ordersItems){
		List<ChartData> chartDatas = new ArrayList<ChartData>();
		
		// 订单状态  1:未付款   2:未发货   3:已发货   4:已签收   5:申请中   6:已退款
		// 删除掉未完成的订单
		List<OrdersItem> ordersItems2 = new ArrayList<OrdersItem>();
		ordersItems2.addAll(ordersItems);
		for(OrdersItem ordersItem : ordersItems) {
			if(ordersItem.getState() != 4 && ordersItem.getState() != 7 && ordersItem.getState() != 8 ) {
				ordersItems2.remove(ordersItems2.indexOf(ordersItem));
			}
		}
		
		// 根据订单时间排序
		Collections.sort(ordersItems2, new Comparator<OrdersItem>() {
			
			@Override
			public int compare(OrdersItem o1, OrdersItem o2) {
				long diff = o1.getOrders2().getOrderTime().getTime()-o2.getOrders2().getOrderTime().getTime();
				if(diff < 0) {
					return -1;
				}
				if(diff > 0) {
					return 1;
				}
				return 0;
			}
		});
		
		ChartData chartData = null;
		long daySecond = 60 * 60 * 24 * 1000;
		for(int i = 0; i < ordersItems2.size(); i++) {
			LocalDateTime localDateTime = ordersItems2.get(i).getOrders2().getOrderTime().toLocalDateTime();
			// 获取到当天0时  24时的时间毫秒数
			long now = ordersItems2.get(i).getOrders2().getOrderTime().getTime() / 1000l;
			long dayTime = now - (now + 8 * 3600000) % daySecond;
			long nextDayTime = dayTime+(24l*3600000l);
			
			chartData = new ChartData(localDateTime.getYear(),localDateTime.getMonthValue(),localDateTime.getDayOfMonth(),null);			
			BigDecimal bigDecimal = new BigDecimal(0);
			for(int j = i; j<ordersItems2.size(); j++ ) {
				// 获取订单的时间的毫秒值 进行比较如果
				long orderTime = ordersItems2.get(j).getOrders2().getOrderTime().getTime();
				if(orderTime > dayTime*1000 && orderTime < nextDayTime*1000) {
					bigDecimal=bigDecimal.add(ordersItems2.get(j).getSubTotal());
				}else {
					i=j;
					break;
				}
			}
			chartData.setDailyIncome(bigDecimal);
			chartDatas.add(chartData);
		}
		return chartDatas;
	}
}
